package dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import dto.Player;

public class DataBase implements Data{
	
	private final String dbUrl;
	
	private static byte[] buffer=null;
	
	private static String LOAD_SQL = "SELECT user_name, point FROM user_point WHERE type_id = 1 ORDER BY point DESC,id limit 0,5;";
	
	private static String SAVA_SQL = "INSERT INTO user_point(user_name, point, type_id) VALUES(?,?,?);";
	
	public DataBase(HashMap<String, String> param) {
		this.dbUrl = param.get("dbUrl");
		try {
			Class.forName(param.get("driver"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public List<Player> loadData() {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<Player> players = new ArrayList<Player>();
		try {
			conn = DriverManager.getConnection(dbUrl);
			stmt = conn.prepareStatement(LOAD_SQL);
			rs = stmt.executeQuery();
			while (rs.next()) {
				players.add(new Player(rs.getString(1), rs.getInt(2)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
//				if (conn != null) conn.close(); 
				if (stmt != null) stmt.close(); 
				if (rs != null) rs.close(); 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return players;
	}

	@Override
	public void savaData(Player players) {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = DriverManager.getConnection(dbUrl);
			stmt = conn.prepareStatement(SAVA_SQL);
			stmt.setObject(1, players.getName());
			stmt.setObject(2, players.getPoint());
			stmt.setObject(3, 1);
			stmt.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
//				if (conn != null) conn.close(); 
				if (stmt != null) stmt.close(); 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static byte[] getBytes(){
		Connection conn = null;
		ResultSet rst = null;
	 	 try {
	 		 String stringSQL="select * from imageTable";
			conn = DriverManager.getConnection("jdbc:sqlite:test.db");
			Statement stm=conn.createStatement();
			rst=stm.executeQuery(stringSQL);
			rst.next();
			buffer=rst.getBytes(2);
	 	 } catch (Exception e) {
			e.printStackTrace();
	 	 }
		return buffer;
	}
}
